<?php
require_once("../../library/openFunction.php");
/*
*微信支付步骤：
*1、进入微信服务号后台，微信支付-开发配置-支付授权目录（精确到文件夹）
*2、进入微信服务号后台，微信支付-商户信息-获取到商户号，并找客户要到六位的微信支付商户平台登录密码，登录此平台，点击左侧的API安全，下载证书，设置api秘钥
*3、apiclient_cert.pem和apiclient_key.pem必须都要有
*/
$ThisUrl = urlencode(root."pay/wxpay/wxpay.php");
$wxpay['appid'] = para("wxAppid");//公众号的唯一标识
$wxpay['mch_id'] = para("wxPayId");//微信支付分配的商户号
$result = payForm("微信网页支付",$kehu);//建立支付记录
$lastPage = getenv("HTTP_REFERER");//上一个页面
if(!empty($result['warn'])){
	$_SESSION['warn'] = $result['warn'];
	header("Location:{$lastPage}");
	exit(0);
}
$wxpay["openid"] = $kehu['wxOpenid'];
$wxpay['out_trade_no'] = $result['orderId'];
$wxpay['total_fee'] = $result['money']*100;//总金额
$wxpay['nonce_str'] = rand(10000,99999).suiji()."zz";//随机字符串，不长于32位。
$wxpay['body'] = "雨木科技";//商品描述
$wxpay['spbill_create_ip'] = $_SERVER['REMOTE_ADDR'];//终端IP
$wxpay['notify_url'] = root."pay/wxpay/wxpayReturn.php";//接收微信支付成功通知地址
$wxpay['trade_type'] = "JSAPI";//交易类型，JSAPI、NATIVE、APP
$wxpay['sign'] = wxsign($wxpay);//获取签名
//将要提交的参数生成xml文件
$xml = arrayToXml($wxpay);
//以post方式提交xml到对应的接口url，并获得prepay_id
$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
$result = Curl($url,$xml);
$prepay = xmlToArray($result);
//使用jsapi调起支付
$wxBridge['appId'] = $wxpay['appid'];
$wxBridge['timeStamp'] = (string)time();//时间戳，数据类型必须为字符串，否则苹果手机报错（调用支付JSAPI缺少参数：timeStamp）
$wxBridge['nonceStr'] = suiji().rand(10000,99999)."aa";
$wxBridge['package'] = "prepay_id=".$prepay['prepay_id'];
$wxBridge['signType'] = "MD5";
$wxBridge['paySign'] = wxsign($wxBridge);
$wxBridgeJson = json_encode($wxBridge);//将所有参数进行json编码
echo head("ad");
?>
<script>
$(document).ready(function(){
	callpay();//执行函数
});
//调用微信JS api 支付
function jsApiCall(){
	WeixinJSBridge.invoke(
		'getBrandWCPayRequest',
		<?php echo $wxBridgeJson; ?>,
		function(res){
			 /**if(res.err_msg == "get_brand_wcpay_request:ok"){
				 var url = "";
			 }else{
			     
			 }**/
			 var url = "<?php echo $lastPage;?>";
			 window.location.href = url;
		}
	)
}
//监听WeixinJSBridgeReady
function callpay(){
	if (typeof WeixinJSBridge == "undefined"){
		if( document.addEventListener ){
			document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		}else if (document.attachEvent){
			document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
			document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		}
	}else{
		jsApiCall();
	}
}
</script>